IF OBJECT_ID('dbo.RptProgressReportDeliverableDetailReport') IS NOT NULL
BEGIN
    DROP PROCEDURE dbo.RptProgressReportDeliverableDetailReport
    IF OBJECT_ID('dbo.RptProgressReportDeliverableDetailReport') IS NOT NULL
        PRINT '<<< FAILED DROPPING PROCEDURE dbo.RptProgressReportDeliverableDetailReport >>>'
    ELSE
        PRINT '<<< DROPPED PROCEDURE dbo.RptProgressReportDeliverableDetailReport >>>'
END
go
-- =======================================================================      
-- Procedure Name: dbo.RptProgressReportDeliverableDetailReport      
--      
-- Author:      Kevin Cashman, Parallax Consulting LLC      
--      
-- Create date: 10/03/2008      
--      
-- Description: Gets Raw data of Progress Deliverables      
--      
-- Serves as a drill down to the Report, RptProgressReportDeliverableReport      
--      
-- Returns:     INT, 0=Success, -1=Error      
--      
-- SampleCall:      
-- RptProgressReportDeliverableDetailReport '5/1/2009','6/10/2009',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'AwaitingDept',41359      
--      
--------------------------------------------------------------------------      
-- Date        Initials  Modification      
--------------------------------------------------------------------------      
-- 04/20/09    RM        Created based on RptSubcontractDeliverableDetailReport.sql      
-- =======================================================================      
                         
                         
CREATE PROCEDURE dbo.RptProgressReportDeliverableDetailReport      
   (        
     @StartDate                         DATETIME,          
     @EndDate                           DATETIME,             
     @DeliverableStatus                 VARCHAR(5000) = NULL,        
     @Institution                       VARCHAR(100) = NULL,        
     @Department                        VARCHAR(100) = NULL,        
     @Unit                              VARCHAR(100) = NULL,        
     @ChiefCode                         VARCHAR(4)   = NULL,        
     @FundNumber                        VARCHAR(1000) = NULL,        
     @PrincipalInvestigator             VARCHAR(100) = NULL,         
     @OriginatingSponsor                VARCHAR(100) = NULL,        
     @Sponsor                           VARCHAR(100) = NULL,             
     @SubcontractSpecialist             VARCHAR(100) = NULL,        
     @SelectedHeaderStatus    VARCHAR(1000)= NULL,        
     @DomainUserId                      INT        
     )         
AS        
BEGIN        
     -- Initial Settings        
     SET NOCOUNT ON        
        
     -- Declare Local Variables        
     DECLARE   @Error              INT,        
               @RowCount           INT,         
      @DeliverableStatusCodes VARCHAR(5000),        
      @DeliverableType    Varchar(50)        
        
     SET    @DeliverableType = NULL        
        
     -- Need to break the filter out to multiple steps, so need a temp table here        
     DECLARE   @Proposals TABLE (        
                    FolderNumber             VARCHAR(12)    NULL,        
                    InfoEdPropNumber         VARCHAR(50)    NULL,        
                    Institution              VARCHAR(50)    NULL,        
                    Department               VARCHAR(50)    NULL,        
                    Unit                     VARCHAR(50)    NULL,        
                    ChiefCode                VARCHAR(4)     NULL,        
                    SponsorName              VARCHAR(75)    NULL,        
                    SponsorTypeName          VARCHAR(50)    NULL,        
                    SecondarySponsor         VARCHAR(75)    NULL,        
                    ProposalShortTitle       VARCHAR(64)    NULL,        
                    PrincipalInvestigator    VARCHAR(64)    NULL,        
                    ProjectStartDate         DATETIME       NULL,        
                    ProjectEndDate           DATETIME       NULL,        
					PreAwardManager    VARCHAR(75)    NULL,       
					PostAwardManager         VARCHAR(75)    NULL,        
                    InstrumentType           VARCHAR(50)    NULL,        
                    SubContractorName        VARCHAR(75)    NULL,        
                    BudgetProjectStartDate   DATETIME       NULL,        
                    BudgetProjectEndDate     DATETIME       NULL,        
                    ProjectAwardedAmount     MONEY  NULL,        
                    BudgetStartDate          DATETIME       NULL,        
                    BudgetEndDate            DATETIME       NULL,        
                    BudgetFundNumber         VARCHAR(20)    NULL,        
                    ExpenseAmount            MONEY          NULL,        
                    IndirectExpenses         MONEY          NULL,        
                    DirectExpenses           MONEY          NULL,        
                    CashBalance              MONEY          NULL,        
                    ReportId                 BIGINT  NULL,        
                    ReportName               VARCHAR(50)    NULL,        
                    REPORTCAT                VARCHAR(80)    NULL,        
                    REPORTSTAT               VARCHAR(80)    NULL,        
                    SubmittedDate            DATETIME       NULL,        
                    DueDate                  DATETIME       NULL,        
                    StatusDate               DATETIME       NULL,        
                    CompletedDate            DATETIME       NULL,        
                    DaysFromDueToCompleted   VARCHAR(5)     NULL,        
                    SubmittedBy              VARCHAR(50)    NULL,        
                    StatusBy                 VARCHAR(50)    NULL,        
                    CompletedBy              VARCHAR(50)    NULL,        
                    PeriodStartDate          DATETIME       NULL,        
                    PeriodEndDate            DATETIME       NULL,        
                    DeliverableComments      VARCHAR(2000)  NULL,        
                    REPORTCAT_CODE           VARCHAR(50)    NULL,        
                    REPORTSTAT_CODE          VARCHAR(50)    NULL,        
                    AgreementId              INT            NULL,        
                    InstitutionId            INT            NULL,        
                    DepartmentId             INT            NULL,        
                    UnitId                   INT            NULL,        
                    SponsorId                INT            NULL, 
                    SponsorAgreementID       VARCHAR(50)    NULL,         
                    PrincipalInvestigatorId  INT            NULL,        
                    SubcontractsYN           CHAR(1)        NULL,        
                    SubContractorId          INT            NULL,        
                    SubOutContractorId       INT            NULL )        
        
     -- ALL checking        
     IF isNull(@DeliverableStatus,'All') IN ('ALL','','0') SET @DeliverableStatus = 'All'        
     IF @Institution IN ('ALL','','0') SET @Institution = NULL        
     IF @Department IN ('ALL','','0') SET @Department = NULL        
     IF @Unit IN ('ALL','','0') SET @Unit = NULL        
     IF @ChiefCode IN ('ALL','','0') SET @ChiefCode = NULL        
     IF @FundNumber IN ('ALL','','0') SET @FundNumber = NULL        
     IF @PrincipalInvestigator IN ('ALL','','0') SET @PrincipalInvestigator = NULL        
     IF @OriginatingSponsor IN ('ALL','','0') SET @OriginatingSponsor = NULL        
     IF @Sponsor IN ('ALL','','0') SET @Sponsor = NULL        
     --IF @Subcontractor IN ('ALL','','0') SET @Subcontractor = NULL        
     IF @SubcontractSpecialist IN ('ALL','','0') SET @SubcontractSpecialist = NULL        
             
     -- Verify firt.        
     IF @DeliverableType IS NOT NULL AND @DeliverableType NOT IN ('ALL','Progress')        
     BEGIN        
          RAISERROR ('ERROR! DeliverableType has an invalid value(%s). Set to a valid DeliverableType and try again.',11,1,@DeliverableType)         
          RETURN -1        
     END        
                       
     -- Set Deliverable Type        
     IF @DeliverableType IS NOT NULL        
          SELECT @DeliverableType = CASE @DeliverableType         
                              WHEN 'ProgressReport' THEN 'REPORTCAT_48'        
                              ELSE 'REPORTCAT_48'   -- ALL        
                           END        
        
     -- Check to see if All is anywhere in the status string        
 IF @DeliverableStatus like '%,All%' OR @DeliverableStatus like '%All,%'        
 BEGIN        
  SELECT @DeliverableStatus = 'All'        
 END        
        
    -- If drilling down to a single status, set the codes here        
 SET   @DeliverableStatusCodes = 'ERROR'        
                
  If @SelectedHeaderStatus is NULL or @SelectedHeaderStatus = 'AwaitingDept' or @DeliverableStatus LIKE '%Awaiting%'  --'REPORTSTAT_43'         
  SELECT  @DeliverableStatusCodes = CASE WHEN  @DeliverableStatus LIKE '%Awaiting%' or @DeliverableStatus = 'All' THEN @DeliverableStatusCodes + ',REPORTSTAT_43' ELSE @DeliverableStatusCodes END        
        
   If @SelectedHeaderStatus is NULL or @SelectedHeaderStatus = 'Complete' or @DeliverableStatus LIKE '%Complete%' --'REPORTSTAT_44'         
  SELECT  @DeliverableStatusCodes = CASE WHEN @DeliverableStatus LIKE '%Complete%' or @DeliverableStatus = 'All' THEN @DeliverableStatusCodes + ',REPORTSTAT_44' ELSE @DeliverableStatusCodes END        
          
  If @SelectedHeaderStatus is NULL or @SelectedHeaderStatus = 'PendingOutYears'  or @DeliverableStatus LIKE '%Pending%'--'REPORTSTAT_45'        
  SELECT    @DeliverableStatusCodes = CASE WHEN @DeliverableStatus LIKE '%Pending%' or @DeliverableStatus = 'All' THEN @DeliverableStatusCodes + ',REPORTSTAT_45' ELSE @DeliverableStatusCodes END        
          
  If @SelectedHeaderStatus is NULL or    @SelectedHeaderStatus = 'ALL' or    @SelectedHeaderStatus = ''     
  SELECT   @DeliverableStatusCodes = CASE WHEN isNull(@DeliverableStatus,'All') = 'All' THEN 'REPORTSTAT_43,REPORTSTAT_44,REPORTSTAT_45' ELSE @DeliverableStatusCodes END        
          
     --Remove error string if other values were added to string        
     SELECT @DeliverableStatusCodes = replace(@DeliverableStatusCodes,'ERROR,','')         
        
     --Check for Errors        
     IF (@DeliverableStatusCodes = 'ERROR' and isNull(@DeliverableStatus,'All') <> 'All')        
     BEGIN        
          RAISERROR ('ERROR! DeliverableStatus has an invalid value. Set to a valid StatusColumn name.',11,1,@DeliverableStatus)         
          RETURN -1        
     END    
             
     -- Performance Issues, Get Secured AgreementIds into a temp table        
     CREATE TABLE   #tt_Agreements  (AgreementId INT)        
             
     INSERT    #tt_Agreements (AgreementId)        
     SELECT    AgreementId        
     FROM      dbo.fnGetSecurityAgreements(@DomainUserId)         
             
	-- Added by Ponraja  Script by Hitesh to improve the performance
	 CREATE CLUSTERED INDEX IC_#tt_Agreements ON #tt_Agreements  
	 (  
	  AgreementId ASC  
	 )         

	 SELECT  ReportId, MIN(ProcessedDate) AS LastDate, REPORTSTAT    
		 INTO #tmpSubContractDeliverables    
		 FROM    dbo.vwInfoEdProgressReportDeliverables     
		 GROUP BY ReportId, REPORTSTAT    
	  
	 
	 CREATE CLUSTERED INDEX IC_#tmpSubContractDeliverables ON #tmpSubContractDeliverables  
	 (  
	  ReportId ASC,  
	  LastDate ASC,  
	  REPORTSTAT ASC  
	 )  

           SELECT D.prop_no,        
                            D.ReportId,        
                            D.ReportName,        
                            D.REPORTCAT_CODE,        
                            D.REPORTCAT,        
                            D.REPORTSTAT,        
                            D.REPORTSTAT_CODE,        
							D.DueDate,        
                            D.SubmittedDate,        
                            D.ProcessedDate AS StatusDate,        
                            D.CompletedDate,        
                            D.SubmittedBy,        
                            D.StatusBy,        
                            D.CompletedBy,        
                            D.PeriodStartDate,        
                            D.PeriodEndDate,        
                            D.Comments,        
                            D.DaysComplCalc     
				INTO #tmpDEL   
                    FROM    dbo.vwInfoEdProgressReportDeliverables D    
                         INNER JOIN (SELECT  ReportId,        
                                                MAX(ProcessedDate) AS LastDate        
                                        FROM    dbo.vwInfoEdProgressReportDeliverables        
                                        GROUP BY ReportId) LAST ON D.ReportId = LAST.ReportId AND         
                                                  D.ProcessedDate = LAST.LastDate


		UPDATE #tmpDEL  
		 SET StatusDate = CONVERT(DATETIME,CONVERT(VARCHAR(12),StatusDate))  
        


     -- Result Set into temp table        
     INSERT    @Proposals        
                    (FolderNumber,        
                    InfoEdPropNumber,        
                    Institution,        
                    Department,        
                    Unit,        
                    ChiefCode,        
                    SponsorName,        
                    SponsorTypeName,        
                    SecondarySponsor,        
                    ProposalShortTitle,        
                    PrincipalInvestigator,        
                    ProjectStartDate,        
                    ProjectEndDate,        
                    PreAwardManager,      
                    PostAwardManager,        
                    InstrumentType,        
                    SubContractorName,        
                    BudgetProjectStartDate,        
                    BudgetProjectEndDate,        
                    ProjectAwardedAmount,        
                    BudgetStartDate,        
                    BudgetEndDate,        
                    BudgetFundNumber,        
                    ExpenseAmount,        
                    IndirectExpenses,        
                    DirectExpenses,        
                    CashBalance,        
                    ReportId,        
                    ReportName,        
                    REPORTCAT,        
                    REPORTSTAT,        
                    SubmittedDate,        
                    DueDate,        
                    StatusDate,        
                    CompletedDate,        
                    DaysFromDueToCompleted,        
                    SubmittedBy,        
                    StatusBy,        
                    CompletedBy,        
                    PeriodStartDate,        
                    PeriodEndDate,        
                    DeliverableComments,        
                    REPORTCAT_CODE,        
                    REPORTSTAT_CODE,        
                    AgreementId,        
                    InstitutionId,        
                    DepartmentId,        
                    UnitId,        
                    SponsorId,     
					SponsorAgreementID,
                    PrincipalInvestigatorId,        
                    SubcontractsYN,        
                    SubContractorId,        
                    SubOutContractorId)        
     SELECT    AI.FolderNumber,        
               AI.InfoEdPropNumber,        
               AI.Institution,        
               AI.Department,        
               AI.Unit,        
               AI.ChiefCode,        
               AI.SponsorName,        
               AI.SponsorTypeName,        
               AI.SecondarySponsor,        
               AI.ProposalShortTitle,        
               AI.PrincipalInvestigator,        
               AI.ProjectStartDate,        
               AI.ProjectEndDate,        
               AI.PreAwardManagerName,      
               AI.PostAwardManagerName,      
               AI.InstrumentType,                                        
               CASE WHEN DEL.REPORTCAT_CODE IN ('REPORTCAT_13','REPORTCAT_40','REPORTCAT_43')         
                    THEN 'N/A'                -- In        
                    ELSE dbo.fnParseSubcontractorName(DEL.ReportName)          -- Out        
               END AS SubContractorName,        
               BUDG.ProjectStartDate AS BudgetProjectStartDate,        
               BUDG.ProjectEndDate AS BudgetProjectEndDate,        
               BUDG.ProjectAwardedAmount,        
               BUDG.BudgetStartDate,        
               BUDG.BudgetEndDate,        
               BUDG.FundNumber AS BudgetFundNumber,        
               BUDG.ExpenseAmount,        
               BUDG.IndirectExpenses,        
               BUDG.DirectExpenses,        
               -1 * isNull(BUDG.CashBalance,0),        
               DEL.ReportId,        
               DEL.ReportName,        
               DEL.REPORTCAT,        
               DEL.REPORTSTAT,        
               DEL.SubmittedDate,        
               DEL.DueDate,        
               DEL.StatusDate,        
               DEL.CompletedDate,        
               DEL.DaysComplCalc AS DaysFromDueToCompleted,        
               ISNULL(DEL.SubmittedBy,'UNASSIGNED') AS Submittedby,        
               DEL.StatusBy,        
               DEL.CompletedBy,        
               DEL.PeriodStartDate,        
               DEL.PeriodEndDate,        
               DEL.Comments AS DeliverableComments,        
               DEL.REPORTCAT_CODE,        
               DEL.REPORTSTAT_CODE,        
               AI.AgreementId,        
               AI.InstitutionId,        
               AI.DepartmentId,        
               AI.UnitId,        
               AI.SponsorId,      
               AI.SponsorAgreementID,  
               AI.PrincipalInvestigatorId,        
               AI.SubcontractsYN,        
               AI.SubContractorId,        
               NULL        
                       
     FROM      dbo.AgrAgreement_Info AI         
                       
               -- Security Issues: Not all Users can see all Agreements!        
               INNER JOIN        
                    #tt_Agreements AUTH ON AI.AgreementId = AUTH.AgreementId        
                            
               INNER JOIN    
                    #tmpDel DEL ON AI.InfoEdPropNumber = DEL.prop_no       
                       
                LEFT OUTER JOIN        
                    -- This function uses the Agreement_Fct table to get Budget and Project data        
                    dbo.fnGetFactTableBudget(@StartDate, @EndDate) BUDG ON AI.AgreementId = BUDG.AgreementId        
                       
     WHERE      (DEL.DueDate BETWEEN @StartDate AND @EndDate) AND        
                (@DeliverableType IS NULL OR DEL.REPORTCAT_CODE IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@DeliverableType))) AND        
                (@DeliverableStatus IS NULL OR DEL.REPORTSTAT_CODE IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@DeliverableStatusCodes))) AND        
                (@Institution IS NULL OR AI.InstitutionId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Institution))) AND        
                (@Department IS NULL OR ISNULL(AI.DepartmentId,-1) IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Department))) AND        
                (@Unit IS NULL OR AI.UnitId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Unit))) AND        
                (@ChiefCode IS NULL OR AI.ChiefCode IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@ChiefCode))) AND                       
                (@PrincipalInvestigator IS NULL OR AI.PrincipalInvestigatorId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria( @PrincipalInvestigator ))) AND        
                (@Sponsor IS NULL OR AI.SponsorId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria( @Sponsor )))         
                       
     ORDER BY  AI.Institution,        
               AI.Department,        
               AI.Unit,        
               AI.FolderNumber,        
               DEL.StatusDate        
                      
        
     SELECT @Error=@@ERROR,@RowCount=@@ROWCOUNT        
     IF @Error!=0        
     BEGIN        
          RAISERROR ('ERROR! Getting Intial Agreement list into TempTable, @Proposals',11,1)        
          DROP TABLE #tt_Agreements        
          RETURN -1        
     END        
             
     -- Even on Success. Drop now.        
     DROP TABLE #tt_Agreements        
             
     -- Return Result Set using additional params        
     SELECT    FolderNumber,        
               InfoEdPropNumber,        
               Institution,        
               Department,        
               Unit,        
               ChiefCode,        
               SponsorName,        
               SponsorTypeName,        
               SecondarySponsor,        
               ProposalShortTitle,        
               PrincipalInvestigator,        
               ProjectStartDate,        
               ProjectEndDate,        
               PreAwardManager,         
               PostAwardManager,        
               InstrumentType,        
               SubContractorName,        
               BudgetProjectStartDate,        
               BudgetProjectEndDate,        
               ProjectAwardedAmount,        
               BudgetStartDate,        
               BudgetEndDate,        
               BudgetFundNumber,        
               ExpenseAmount,        
               IndirectExpenses as DirectExpenses,        
               DirectExpenses as IndirectExpenses,        
               CashBalance,        
               ReportId,        
               ReportName,        
               REPORTCAT,        
               REPORTSTAT,        
               SubmittedDate,        
               DueDate,        
               StatusDate,        
               CompletedDate,        
               DaysFromDueToCompleted,        
               SubmittedBy,        
               StatusBy,        
               CompletedBy,        
               PeriodStartDate,        
               PeriodEndDate,        
               DeliverableComments,        
               REPORTCAT_CODE,        
               REPORTSTAT_CODE,        
               AgreementId,        
               InstitutionId,        
               DepartmentId,        
               UnitId,        
               SponsorId,        
			   SponsorAgreementID,
               PrincipalInvestigatorId,        
               SubcontractsYN,        
               SubContractorId,        
               SubOutContractorId        
     FROM      @Proposals        
     WHERE     (@FundNumber IS NULL OR BudgetFundNumber IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@FundNumber))) AND        
               (@OriginatingSponsor IS NULL OR SecondarySponsor = @OriginatingSponsor ) AND        
               -- If user is drilling down, this would be passed...        
               --(@Subcontractor IS NULL OR SubContractorName = @SubContractor) AND        
               (@SubcontractSpecialist IS NULL OR SubmittedBy = @SubcontractSpecialist OR        
               (@SubcontractSpecialist = 'UNASSIGNED' AND SubmittedBy IS NULL ))         
             
     SELECT @Error=@@ERROR,@RowCount=@@ROWCOUNT        
     IF @Error!=0        
     BEGIN        
          RETURN -1        
     END        
        
     -- Return Success        
     RETURN 0        
            
END 
go
IF OBJECT_ID('dbo.RptProgressReportDeliverableDetailReport') IS NOT NULL
    PRINT '<<< CREATED PROCEDURE dbo.RptProgressReportDeliverableDetailReport >>>'
ELSE
    PRINT '<<< FAILED CREATING PROCEDURE dbo.RptProgressReportDeliverableDetailReport >>>'
go


GRANT EXECUTE ON dbo.RptProgressReportDeliverableDetailReport TO InsightReport,Insight
go

